import React, { PureComponent } from "react";
import { Card, Spin, Table, Button } from "antd";
import dynamic from "umi/dynamic";
import { connect } from "dva";
import { delay } from "utils/comm";
import { getMenuRouter } from "components/layouts/menuFn";
import TransferSeclet from "components/transferSecletModal/TransferSeclet";
import PageLayout from "components/pageconlayout/PageLayout";
import { initAppListData } from "../flowlist/Tools/serviceHelper";
import {
  emptyParams,
  getColumns,
  getPageProps,
  getRowSelectionProps,
  handlePageChange,
  renderStatus,
  getEllipsisCell,
  initData,
} from "./taskListHelper";

import styles from "./TaskList.less";

const QueryExtra = dynamic({ loader: async () => {
  await delay(500);
  return import("../QueryExtra");
} });
const AdvancedFilter = dynamic({ loader: async () => {
  await delay(800);
  return import("../AdvancedFilter");
} });
const Catalogue = dynamic({ loader: async () => {
  await delay(100);
  return import("components/catalogue/Catalogue");
} });

@connect(({ appListMenu, FlowMonitor, loading, Public }) => ({
  appListMenu,
  FlowMonitor,
  loading,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class TaskList extends PureComponent {
  state = {
    filterVisible: false,
    selectedKeys: [],
    selectedTaskKeys: [],
    page: {
      pageNum: 1,
      pageSize: 10,
    },
    transferVisible: false,
  };

  getColumns = getColumns.bind(this);

  getEllipsisCell = getEllipsisCell.bind(this, styles.ellipsis);

  getMenuRouter = getMenuRouter.bind(this);

  getPageProps = getPageProps.bind(this);

  getRowSelectionProps = getRowSelectionProps.bind(this);

  handlePageChange = handlePageChange.bind(this);

  initAppListData = initAppListData.bind(this);

  initData = initData.bind(this);

  renderStatus = renderStatus.bind(this, styles.statusDot);

  searchParams = { ...emptyParams };

  selectedProcesses = [];

  componentDidMount() {
    this.initAppListData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "FlowMonitor/clearData" });
  }

  getFormThis = (formThis, type = "advancedFilter") => {
    if (type === "advancedFilter") {
      this.filterForm = formThis;
    } else if (type === "queryExtra") {
      this.queryExtraForm = formThis;
    }
  };

  resetPageData = () => {
    const { dispatch } = this.props;
    this.searchParams = { ...emptyParams };
    dispatch({ type: "FlowMonitor/clearData" });
    this.setState({
      page: { pageNum: 1, pageSize: 10 },
      filterVisible: false,
    });
    if (this.filterForm) this.filterForm.handleReset();
    if (this.queryExtraForm) this.queryExtraForm.handleReset();
    this.initAppListData();
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    return { ...this.searchParams, pageNum, pageSize };
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    if (this.filterForm) this.filterForm.handleSubmit();
    if (this.queryExtraForm) this.queryExtraForm.handleSubmit();
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  /* 我的流程单选择 */
  handleTypeSelect = (selectedKeys = [], e, preId, nomalSelectedKeys) => {
    const Keys = selectedKeys[0].split("|");

    const newSelectkeys = nomalSelectedKeys || selectedKeys;
    // console.log(e.node.props.isLeaf)
    if (!(selectedKeys && selectedKeys[0].length > 0)) return;
    if (e.node.props.isLeaf) {
      // 子节点
      this.searchParams = {
        ...this.searchParams,
        busiId: selectedKeys[0],
        appId: "",
        tenantId: "",
      };
    } else if (Keys[0] === "tenant") {
      this.searchParams = {
        ...this.searchParams,
        tenantId: Keys[Keys.length - 1],
        appId: "",
        busiId: "",
      };
    } else {
      this.searchParams = {
        ...this.searchParams,
        appId: Keys[Keys.length - 1],
        busiId: "",
        tenantId: "",
      };
    }
    if (this.filterForm) this.filterForm.handleReset();
    if (this.queryExtraForm) this.queryExtraForm.handleReset();
    this.setState({ selectedKeys: newSelectkeys });
    this.handleSearch();
  };

  // 查询参数改变
  handleParamsChange = (newparams) => {
    this.searchParams = { ...this.searchParams, ...newparams };
  };

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  };

  renderUserSelect() {
    const { transferVisible, selectedTaskKeys } = this.state;
    const { dispatch } = this.props;
    return (
      <TransferSeclet
        dispatch={dispatch}
        selectedTaskKeys={selectedTaskKeys}
        visible={transferVisible}
        initData={() => {this.initAppListData()}}
        onCancel={() => {
          this.setState({
            transferVisible: false,
          })
        }}
        initSelectedTaskKeys={() => {
          this.setState({
            selectedTaskKeys: [],
          })
        }}
        wrapClassName={styles.user_modal}
      />
    );
  }

  render() {
    const { loading, dispatch, appListMenu, FlowMonitor } = this.props;
    const {
      page: { pageNum, pageSize },
      filterVisible,
      selectedKeys,
      selectedTaskKeys,
    } = this.state;
    const { taskData = [], taskTotalCount: totalCount = 0 } = FlowMonitor;
    const { appListMenuData = [] } = appListMenu;
    // const listLoading = loading.models.appListMenu;
    const taskLoading = loading.effects["FlowMonitor/getTaskList"];
    const menuListLoading = loading.effects["appListMenu/getAppListData"];
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              title="应用业务目录"
              style={{ width: "100%", height: "100%" }}
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104 - 10,
              }}
            >
              <Spin spinning={menuListLoading} delay={300}>
                <Catalogue
                  CatalogueData={appListMenuData}
                  treeNodeSelect={this.handleTypeSelect}
                  selectedKeys={selectedKeys}
                  // defaultSelectedKeys={[this.processType]}
                />
              </Spin>
            </Card>
          }
          rightContent={
            <Card
              className={styles.rightCon}
              title={
                <div className={styles.container}>
                  <span className={styles.title}>
                    任务列表(
                    {totalCount}
                    )
                  </span>
                  <Button
                    disabled={selectedTaskKeys?.length === 0}
                    onClick={() => {
                      this.setState({
                        transferVisible: true,
                      })
                    }}
                    style={{marginLeft: 10}}
                  >
                    转办
                  </Button>
                </div>
              }
              extra={
                <QueryExtra
                  handleParamsChange={this.handleParamsChange}
                  onSearch={this.handleSearch}
                  visible={filterVisible}
                  getFormThis={this.getFormThis}
                  handleFilterVisible={this.handleFilterVisible}
                  placeholder="请输入任务名称"
                  keyName="taskName"
                />
              }
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
              }}
              style={{ width: "100%" }}
            >
              <AdvancedFilter
                userTitle="处理人"
                dispatch={dispatch}
                onSearch={this.handleSearch}
                handleParamsChange={this.handleParamsChange}
                visible={filterVisible}
                getFormThis={this.getFormThis}
                renderType="task"
              />
              <Table
                className={styles.listcon}
                columns={this.getColumns()}
                dataSource={taskData}
                loading={taskLoading}
                rowKey="taskId"
                rowSelection={this.getRowSelectionProps(selectedTaskKeys)}
                pagination={this.getPageProps(pageNum, pageSize, totalCount)}
              />
            </Card>
          }
        />
        {this.renderUserSelect()}
      </div>
    );
  }
}

export default TaskList;
